////////////////////////
// Constants &	      //
// globals	      //
////////////////////////

var CONTROLBAR_TIMEOUT = 2000;
var VERBOSE = 0;
var TESTING = 0;
var SOUNDS_LIST = ["Ding", "Chimes", "-"];
var SKINS_LIST = ["Default", "Gold", "Classic", "White"];
var _player = null;
var _wndOptions = null;
var _currentClock = -1;
var _controlbarVisibility = 0;

////////////////////////
// Creation	      //
// destruction	      //
////////////////////////

function Init() {
  Trace("init");
  Tests();
  InitPlayer();
  LoadClocks();
  _currentClock = _clocks.length;

  // Set default preferences
  SetDefault();
  // Init gfx
  InitGraphical();
  // Start the timer
  setInterval("Timer();", 1000);
}

function InitGraphical() {
  // Load skin data
  LoadSkin();

  // Load tooltip
  PlayPause.tooltip = STARTSTOP_TT;
  Previous.tooltip = PREVIOUS_TT;
  Stop.tooltip = STOP_TT;
  Next.tooltip = NEXT_TT;
  // Draw interface
  DrawInfo("Time");
  SetControlBar(false);
}


function Destroy() {
  SaveClocks();
}

// "H:mm" -> "m:ss" -> "s"
// ""
function SetDefault() {
  options.defaultValue("timeFormat") = "H:mm:ss";
  if (TESTING) {
    options.defaultValue("skinDir") = "Classic";
    options.defaultValue("sound") = "None";
  } else {
    options.defaultValue("skinDir") = "Gold";
    options.defaultValue("sound") = "Chimes";
  }
  options.defaultValue("currentClock") = 0;
}

/////////////////////
// Events 	   //
// handling	   //
/////////////////////

function OnMouseOver() {
  if (_controlbarVisibility == 0)
    SetControlBar(true);
  _controlbarVisibility = 1;
}
function OnMouseOut() {
  setTimeout("SetControlBar(false);", CONTROLBAR_TIMEOUT);
  _controlbarVisibility = 0;
}

function OnNext() {
  _currentClock = (_currentClock + 1) % (_clocks.length+1);
  // hide inactives
  if (_currentClock != _clocks.length && _clocks[_currentClock].active == false)
    OnNext();
  // Display
  DrawDetails();
  var date = new Date();
  if (_currentClock != _clocks.length &&
      _currentClock != -1)
    date = _clocks[_currentClock].GetDate();
  DrawTime(date, options("timeFormat"));
}

function OnPrevious() {
  _currentClock--;
  if (_currentClock < 0)
    _currentClock = _clocks.length;
  // hide inactives
  if (_currentClock != _clocks.length && _clocks[_currentClock].active == false)
    OnPrevious();
  // Display (merge with onnext!)
  DrawDetails();
  var date = new Date();
  if (_currentClock != _clocks.length &&
      _currentClock != -1)
    date = _clocks[_currentClock].GetDate();
  DrawTime(date, options("timeFormat"));
}

function OnPlayPause() {
  if (_currentClock == _clocks.length)
    return;
  if (_clocks[_currentClock].type == 0)
    return;
  if (_clocks[_currentClock].state == 1) {
    _clocks[_currentClock].state = 2;
  } else {
    _clocks[_currentClock].state = 1;
  }
  DrawDetails();
}

function OnStop() {
  if (_currentClock == _clocks.length)
    return;
  _clocks[_currentClock].time = 0;
  _clocks[_currentClock].state = 2;
  DrawDetails();
  // TODO stop the ringing!
}

function OnOptionChanged() {
  if (1)
    Trace("OnOptionChanged "+event.propertyName+" "+options(event.propertyName));
}


///////////////////////
// Timer	     //
// Operations	     //
///////////////////////

function Timer() {
  // update the timers!
  var i = 0;
  for (i = 0; i < _clocks.length; i++) {
    _clocks[i].Check();
  }
  // show the time
  var date = new Date();
  if (_currentClock != _clocks.length &&
      _currentClock != -1)
    date = _clocks[_currentClock].GetDate();
  DrawTime(date, options("timeFormat"));
}

/////////////////////
// Display	   //
// elements	   //
/////////////////////

// Update the controlbar's info
function DrawDetails() {
  if (_currentClock == _clocks.length) {
    DrawInfo("Time");
    return;
  } else
    DrawInfo(_clocks[_currentClock].name);
  if (_clocks[_currentClock].state == 2 || _clocks[_currentClock].state == 0) {
    SetButtonImages(PlayPause, "play");
  } else {
    SetButtonImages(PlayPause, "pause");
  }
}

function SetButtonImages(element, name) {
    element.image = "skins/"+options("skinDir")+"/"+name+".png";
    element.downImage = "skins/"+options("skinDir")+"/"+name+"down.png";
    element.overImage = "skins/"+options("skinDir")+"/"+name+"over.png";
}

function SetControlBar(state) {
  if (state == false && _controlbarVisibility == 1)
    return;
  // bg / buttons / label
  PlayPause.visible = state;
  Stop.visible = state;
  Previous.visible = state;
  Next.visible = state;
  bg.visible = state;
  Info.visible = state;
}

function DrawInfo(data) {
  Trace("drawinfo");
  Info.innerText = data;
}

function DrawTime(data, format) {
  var time = formatDate(data, format);
  var i;
  var size = time.length;
  var temp = "    ";
  if (size < 8) {
    time = temp.substring(0, Math.floor((8-size)/2))+time+temp.substring(0, 8-Math.floor((8-size)/2)-size);
  }
  for (i = 1; i < 9; i++) {
    var name = time.charAt(i-1);
    if (name == ':')
      name = "separator";
    if (name == ' ')
      name = "space";
    eval("Time"+i+".src='skins/"+options("skinDir")+"/"+name+".png';");
  }
}

//////////////////////
// Xml 		    //
// utilities	    //
//////////////////////

function LoadSkin() {
  // Load x, y
  bg.src = "skins/"+options("skinDir")+"/background.png";
  SetButtonImages(PlayPause, "play");
  DrawDetails();
  SetButtonImages(Stop, "stop");
  SetButtonImages(Next, "next");
  SetButtonImages(Previous, "previous");
  try {
    Trace("LoadSkin");
    var doc = new DOMDocument();
    doc.loadXML(storage.openText("skins/"+options("skinDir")+"/data.xml"));
    var images = doc.getElementsByTagName("element");
    for(var i = 0; i < images.length; i++) {
      var e = images[i];
      var name = e.getAttribute("id");
      if (name != "view") {
	eval(name+".x="+e.getAttribute("x")+";");
	eval(name+".y="+e.getAttribute("y")+";");
      } else {
	resizeTo(e.getAttribute("w"), e.getAttribute("h"));
      }
    }
  } catch(e) {
    alert(e.message+"\r\n\r\nPlease try again.");
  }
}

//////////////////////
// Utilities	    //
//////////////////////
function InitPlayer() {
  Trace("InitPlayer");
  _player = new ActiveXObject("WMPlayer.OCX");
  _player.uiMode = "none";
  _player.settings.setMode("autoRewind", true);
  _player.settings.autoStart = false;
}

function GetAbsolutePath(file) {
  path = "";
  var fso = new ActiveXObject("Scripting.FileSystemObject");
  if (fso.FileExists("c:\\WINNT\\Temp\\"+file)) {
    return "c:\\WINNT\\Temp\\"+file;
  } else if (fso.FileExists("c:\\windows\\Temp\\"+file)) {
    return "c:\\windows\\Temp\\"+file;
  }
  return storage.extract("sounds/"+file);
  // if someday there's a better way to do that, use code below
//   // extract
//   path = storage.extract("mysound.wav");
//   var w = new ActiveXObject("Scripting.WScript");
//   var a = w.ScriptFullName;
//   Trace(a+"asd");
//   return;
//   var sys = system.filesystem;
//   var path = sys.GetParentFolderName(w.ScriptFullName);
//   Trace(path);
//   // get the base path
//   return;
//   Trace(storage.extract("mysound.wav"));
//   var a = storage.openText("c:\asdasd");
//   if (a == null)
//     Trace("asd");
//   return;
  return file;
}

function PlaySound(file, replay) {
  try {
    // add file to playlist
    var playlist = _player.newPlaylist("", "");
    var newMedia = _player.newMedia(file);
    for (var i = 0; i < replay; i++)
      playlist.appendItem(newMedia);
    _player.currentPlaylist = playlist;
    playlist = null;
    newMedia = null;
    // play the sound
    _player.controls.play();
  } catch(e) {
    Trace(e);
  }
}

function Mail() {
  // TODO
}

function Execute(target) {
  var axWS = new ActiveXObject("WScript.Shell");
  var axFS = new ActiveXObject("Scripting.FileSystemObject");
  //  target = axFS.GetFile(target).ShortPath;
  axWS.Run(target);
}

function Trace(data) {
  if (VERBOSE)
    debug.trace(data);
}


//////////////////
// Tests        //
//////////////////

function Tests() {
  Trace("Tests");
  if (TESTING) {
    Trace("REMOVE ALL OPTIONS");
    options.removeAll();
  }
//   return;
//    NewTimer();
//    NewAlarm();
//  Trace(_clocks[0].ListName());
  //  SaveClocks();
  //GetAbsolutePath("ads");
  //PlaySound(GetAbsolutePath("mysound.wav"), 1);
  //  PlaySound("C:\\Documents and Settings\\mbelmont\\My Documents\\My Stuffs\\api\\my\\mysound.wav", 1);
}
